package com.apestech.framework.db.session;

import com.apestech.framework.db.PsmtUtil;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.db.SqlTemplate;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;

public class ForProcedure {
    private SqlTemplate cn;
    private SqlSession session;

    public ForProcedure(SqlSession session){
        this.session=session;
        this.cn=session.getCn();
    }

    public JSONObject callproc(String procId, JSONObject param) throws Exception {
        procId=procId.toUpperCase();
        JSONArray plist=session.getProcedure(procId);
        if(plist==null){
            throw new Exception("请检查下过程名的正确性！");
        }
        String sql="{call "+procId;  //{call proc_Ins_Dept2(?,?,?,?)}
        int len=plist.size();
        if(len>0){
            sql=sql+"(";
            for(int i=0; i<len; i++){
                if(i>0) {
                    sql=sql+",";
                }
                sql=sql+"?";
            }
            sql=sql+")";
        }
        sql=sql+"}";
        JSONArray params=new JSONArray();
        for(int i=0; i<len; i++){
            JSONObject p=plist.get(i);
            JSONObject m=new JSONObject();
            m.put("type", p.getString("TYPE_NAME"));
            m.put("direction", p.getString("TYPE"));
            String key=p.getString("COLUMN_NAME");
            m.put("key", key);
            m.put("value", param.get(key));
            params.add(m);
        }
        System.out.println(PsmtUtil.getPrintProg(procId, params));
        return cn.callProc(sql, params);
    }


}
